/*===========================================================================
  Copyright (C) 2014 by the Okapi Framework contributors
-----------------------------------------------------------------------------
  This library is free software; you can redistribute it and/or modify it 
  under the terms of the GNU Lesser General Public License as published by 
  the Free Software Foundation; either version 2.1 of the License, or (at 
  your option) any later version.

  This library is distributed in the hope that it will be useful, but 
  WITHOUT ANY WARRANTY; without even the implied warranty of 
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 
  General Public License for more details.

  You should have received a copy of the GNU Lesser General Public License 
  along with this library; if not, write to the Free Software Foundation, 
  Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

  See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html
===========================================================================*/

package net.sf.okapi.lib.xliff2.renderer;

import java.util.Iterator;
import java.util.Map;
import java.util.Stack;

import net.sf.okapi.lib.xliff2.NSContext;
import net.sf.okapi.lib.xliff2.core.Fragment;
import net.sf.okapi.lib.xliff2.core.Tag;

/**
 * Implements {@link IFragmentRenderer} for the XLIFF 2 format.
 * <p>Note that the inline tags representation uses only <code>&lt;sc>/&lt;ec></code>
 * and <code>&lt;sm>/&lt;em><code>.
 */
public class XLIFFFragmentRenderer implements IFragmentRenderer {

	private Fragment frag;
	private Stack<NSContext> nsStack;
	private Map<Tag, Integer> tagsStatus;
	
	/**
	 * Creates a new {@link XLIFFFragmentRenderer} object for a given fragment and namespace context.
	 * @param fragment the fragment to associate with this renderer.
	 * @param nsStack the namespace stack (can be null).
	 */
	public XLIFFFragmentRenderer (Fragment fragment,
		Stack<NSContext> nsStack)
	{
		set(fragment, nsStack);
	}

	@Override
	public void set (Fragment fragment,
		Stack<NSContext> nsStack)
	{
		this.frag = fragment;
		this.nsStack = nsStack;
	}
	
	@Override
	public Iterator<IFragmentObject> iterator () {
		// Get the snapshot of the tags' status
		tagsStatus = frag.getOwnTagsStatus();
		// Create the new iterator
		return new Iterator<IFragmentObject>() {
			
			Iterator<Object> iter = frag.iterator();
			
			@Override
			public void remove () {
				iter.remove();
			}
			
			@Override
			public IFragmentObject next () {
				return new XLIFFFragmentObject(iter.next(), tagsStatus, nsStack);
			}
			
			@Override
			public boolean hasNext () {
				return iter.hasNext();
			}
		};
	}

}
